package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.IntentUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.apkextract.lib.model.AeUtil;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.AppAdapter;
import flc.ast.bean.ApkBean;
import flc.ast.databinding.ActivityAppBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.GeneralEvtDialog;
import stark.common.basic.utils.RxUtil;

public class AppActivity extends BaseAc<ActivityAppBinding> {

    private AppAdapter appAdapter;
    private int oldPosition = 0;
    private boolean isEdit = false;
    private String selApp = "";

    @Override
    protected int onCreate() {
        return R.layout.activity_app;
    }

    @Override
    public void onBackPressed() {
        if (isEdit) {
            cancelEdit();
        } else {
            finish();
        }
    }

    @Override
    protected void initView() {
        mDataBinding.ivAppBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivAppEdit.setOnClickListener(this);
        mDataBinding.tvAppDelete.setOnClickListener(this);

        mDataBinding.rvAppList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        appAdapter = new AppAdapter();
        mDataBinding.rvAppList.setAdapter(appAdapter);
        appAdapter.setOnItemClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAppEdit://编辑
                isEdit = true;
                mDataBinding.ivAppEdit.setVisibility(View.GONE);
                mDataBinding.tvAppDelete.setVisibility(View.VISIBLE);
                appAdapter.setEdit(isEdit);
                appAdapter.notifyDataSetChanged();
                mDataBinding.tvAppDelete.setText(getString(R.string.delete_text,0));
                break;
            case R.id.tvAppDelete://卸载
                if (TextUtils.isEmpty(selApp)) return;
                uninstallApp(selApp);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            appAdapter.getItem(oldPosition).setSelected(false);
            appAdapter.notifyItemChanged(oldPosition);
            oldPosition = position;
            appAdapter.getItem(position).setSelected(true);
            appAdapter.notifyItemChanged(position);
            selApp = appAdapter.getItem(position).pkgName;
            mDataBinding.tvAppDelete.setText(getString(R.string.delete_text,1));
        } else {
            lookAppDetail(appAdapter.getItem(position).pkgName);
        }
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        showDialog(getString(com.stark.common.res.R.string.loading));
        RxUtil.create(new RxUtil.Callback<List<ApkBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<ApkBean>> emitter) {
                List<String> listSys = AeUtil.getNoSystemInstalledPackageNames();
                List<ApkBean> apkBeans = new ArrayList<>();
                ApkBean bean;
                for (String packageName : listSys) {
                    bean = new ApkBean();
                    bean.pkgName = packageName;
                    apkBeans.add(bean);
                }
                emitter.onNext(apkBeans);
            }

            @Override
            public void accept(List<ApkBean> packageNames) {
                if (!CollectionUtils.isEmpty(packageNames)) {
                    mDataBinding.rvAppList.setVisibility(View.VISIBLE);
                    mDataBinding.tvAppNoData.setVisibility(View.GONE);
                    appAdapter.setList(packageNames);
                } else {
                    mDataBinding.rvAppList.setVisibility(View.GONE);
                    mDataBinding.tvAppNoData.setVisibility(View.VISIBLE);
                }
                dismissDialog(500L);
            }
        });
    }

    //查看应用详情
    private void lookAppDetail(String packageName) {
        Intent intent = IntentUtils.getLaunchAppDetailsSettingsIntent(packageName);
        try {
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //卸载应用
    private void uninstallApp(String packageName) {
        new GeneralEvtDialog.Builder(this)
                .title(getString(com.stark.common.res.R.string.prompt))
                .content(getString(R.string.is_uninstall_text) + AppUtils.getAppName(packageName))
                .rightBtnListener(v -> {
                    if (AppUtils.isAppSystem(packageName)) {
                        ToastUtils.showShort(R.string.app_is_system);
                        return;
                    }
                    AppUtils.uninstallApp(packageName);
//                    lookAppDetail(packageName);
                    saveRecord();
                })
                .rightBtnTextColor(Color.parseColor("#0000FF"))
                .build()
                .show();
    }

    private void saveRecord() {
        List<ApkBean> listSp = AppSpUtils.getUninstallRecordList();
        if (listSp == null) listSp = new ArrayList<>();
        listSp.add(0, appAdapter.getItem(oldPosition));
        AppSpUtils.saveUninstallRecordList(listSp);
    }

    //取消编辑
    private void cancelEdit() {
        selApp = "";
        isEdit = false;
        mDataBinding.ivAppBack.setVisibility(View.VISIBLE);
        mDataBinding.ivAppEdit.setVisibility(View.VISIBLE);
        mDataBinding.tvAppDelete.setVisibility(View.GONE);
        appAdapter.setEdit(isEdit);
        for (ApkBean bean : appAdapter.getValidData()) {
            bean.setSelected(false);
        }
        appAdapter.notifyDataSetChanged();
    }

}